package com.hubu.sugon.service.impl;

import com.github.pagehelper.PageInfo;
import com.hubu.sugon.entity.PageInfoResult;
import com.hubu.sugon.entity.Result;
import com.hubu.sugon.entity.RetCodeEnum;
import com.hubu.sugon.service.CommonService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommonServiceImpl implements CommonService {
    @Override
    public <T> Result initReturnResult(int code, boolean success, String msg, T data) throws Exception{
        Result<T> result = new Result<T>();
        result.setErrmsg(msg);
        result.setCode(code);
        result.setSuccess(success);
        result.setData(data);
        return  result;
    }

    @Override
    public <T> Result initReturnResult(RetCodeEnum retCodeEnum, T data, boolean success, String msg) {
        Result<T> result = new Result<>();
        result.setCode(retCodeEnum.getCode());
        if(StringUtils.isEmpty(msg)){
            result.setErrmsg(retCodeEnum.getDesc());
        }else{
            result.setErrmsg(msg);
        }
        result.setSuccess(success);
        result.setData(data);
        return  result;
    }

    @Override
    public Result initReturnResult(RetCodeEnum retCodeEnum, boolean success, String msg) {
        return initReturnResult(retCodeEnum, null , success, msg);
    }

    @Override
    public boolean checkExistsEmptyFields(Object ... fields) {
        for (Object field: fields) {
            if(StringUtils.isEmpty(field)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public <T> Result returnResult(String key, T object, String message) throws Exception {
        if(StringUtils.isEmpty(message)) {
            message = "查询成功";
        }
        Map<String, Object> retMap = new HashMap<String, Object>(16);
        if(null == object) {
            retMap.put(key, new HashMap<>(1));
        } else {
            retMap.put(key, object);
        }

        return initReturnResult(RetCodeEnum.CODE_200, retMap,true, message);
    }

    @Override
    public Integer convertObjectToInteger(Object value) {
        return Integer.valueOf(value.toString());
    }

    @Override
    public <T> PageInfoResult toPage(List<T> list) {
        PageInfo<T> pageInfo = new PageInfo(list);
        PageInfoResult<T> pageInfoResult = new PageInfoResult<>();
        pageInfoResult.setRows(list);
        pageInfoResult.setPageNum(pageInfo.getPageNum());
        pageInfoResult.setPageSize(pageInfo.getPageSize());
        pageInfoResult.setTotal(pageInfo.getTotal());
        return pageInfoResult;
    }
}
